window.onload = function() {
    const canvas = document.getElementById("myCanvas");
    const context = canvas.getContext("2d");

    let lineWidth = 1;
    var lines = [];
    var huabi = document.querySelector('.huabi');
    var react = document.querySelector('.react');
    var xianduan = document.querySelector('.xian');
    var yuan = document.querySelector('.yuan');
    var down = document.querySelector('.down');
    var text = document.querySelector('.text');
    var erase = document.querySelector('.erase');
    var RectangleCheckbox = document.getElementById('RectangleCheckbox');
    var xuxian = document.querySelector('.dropdown-content').querySelectorAll('a');
    var xu = document.querySelector('.xu');
    var sanjiao = document.querySelector('.sanjiao');
    var jiantou = document.querySelector('.jiantou');
    var wenben = document.querySelector('#wenben');
    var txtBox = document.querySelector('.txtBox');

    var textsize = 25,
        textcss = "华文行楷";
    var shu = 0;
    var posX, posY;
    // var dropbtn = document.querySelector('.dropbtn');
    // var wanggeCheckbox = document.getElementById('wanggeCheckbox');
    // wangge = false;
    var rectangle = RectangleCheckbox.checked;
    var drawingSurfaceImageData;
    var lastX,
        lastY;
    mousedown = {};
    rubberbandRect = {};
    var xiancss = {};
    // var huabi = document.querySelector('.huabi');

    // 画网格
    function drawGrid(color, stepX, stepY) {
        context.save();
        context.lineWidth = 0.5;
        context.strokeStyle = color;
        context.setLineDash([]);
        context.beginPath();
        for (var i = stepX + 0.5; i < canvas.width; i += stepX) {
            context.beginPath();
            context.moveTo(i, 0 + 0.5);
            context.lineTo(i, canvas.height + 0.5)
            context.stroke();
        }
        for (var i = stepY + 0.5; i < canvas.height; i += stepY) {
            context.beginPath();
            context.moveTo(0 + 0.5, i);
            context.lineTo(canvas.width, i);
            context.stroke();
        }

        context.restore();
        context.closePath();
    }

    // 换颜色
    let color;
    var colord = document.querySelector('.colordiv').querySelectorAll('span');
    var colors = document.querySelector('#colors');
    for (var i = 0; i < colord.length; i++) {
        colord[i].onclick = function() {
            // alert(backgroundColor.value);
            // color = e.target.value;
            color = this.style.backgroundColor;
        }
    }
    var cishu = 1;

    colors.addEventListener('change', e => {
        color = e.target.value;
        if (cishu == 1) {
            colord[8].style.backgroundColor = color;
            cishu = 2;
        } else {
            colord[9].style.backgroundColor = colord[8].style.backgroundColor;
            colord[8].style.backgroundColor = color;
        }

        // context.strokeStyle = color.value;
    });
    // 画笔粗细
    document.querySelector('#select').onchange = function(e) {
        lineWidth = e.target.value;
    };
    document.querySelector('#size').onchange = function(e) {
        textsize = e.target.value;
    };
    document.querySelector('#yangshi').onchange = function(e) {
        textcss = e.target.value;
        // alert(e.target.value);
    };
    drawGrid('lightgray', 10, 10);
    // huaban
    var huaban = {
            type: "huabi",
            status: false,
            beginX: 0,
            beginY: 0,
            imageData: null,
            huabiFn: function(eve) {
                context.setLineDash([]);
                context.strokeStyle = color;
                context.lineWidth = lineWidth;
                // context.beginPath();
                context.lineTo(eve.offsetX, eve.offsetY);
                context.stroke();
                // context.closePath();
            },
            reactFn: function(e) {
                // var x = e.pageX - canvas.offsetLeft;
                // var y = e.pageY - canvas.offsetTop;

                context.strokeStyle = color;
                context.lineWidth = lineWidth;
                var x = e.offsetX;
                var y = e.offsetY;
                context.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
                drawGrid('lightgray', 10, 10);
                if (huaban.imageData != null) {
                    context.putImageData(huaban.imageData, 0, 0, 0, 0, canvas.offsetWidth, canvas.offsetHeight);
                }
                context.beginPath();
                context.rect(huaban.beginX, huaban.beginY, x - huaban.beginX, y - huaban.beginY);
                context.stroke();
                context.closePath();
            },
            xianduanFn: function(eve) {
                context.clearRect(0, 0, 1000, 480);
                drawGrid('lightgray', 10, 10);
                drawOldLines();
                if (huaban.imageData != null) {
                    context.putImageData(huaban.imageData, 0, 0, 0, 0, canvas.offsetWidth, canvas.offsetHeight);
                }
                context.strokeStyle = color;
                context.lineWidth = lineWidth;
                context.beginPath();
                context.moveTo(huaban.beginX, huaban.beginY);
                context.lineTo(eve.offsetX, eve.offsetY);
                context.stroke();
            },
            xuxianFn: function(eve) {
                context.lineTo(eve.offsetX, eve.offsetY);
                context.stroke();
            },
            sanjiaoFn: function(e) {
                var x = e.offsetX;
                var y = e.offsetY;
                context.strokeStyle = color;
                context.lineWidth = lineWidth;
                context.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
                drawGrid('lightgray', 10, 10);
                if (huaban.imageData != null) {
                    context.putImageData(huaban.imageData, 0, 0, 0, 0, canvas.offsetWidth, canvas.offsetHeight);
                }
                context.beginPath();
                var tx = x - huaban.beginX;
                var ty = y - huaban.beginY;
                var txy = Math.sqrt(tx ** 2 + ty ** 2); //圆心到角的距离
                context.moveTo(huaban.beginX + txy * Math.sin(Math.PI * 2 / 3), huaban.beginY + txy * Math.cos(Math.PI * 2 / 3));
                context.lineTo(huaban.beginX + txy * Math.sin(Math.PI * 2 / 3 * 2), huaban.beginY + txy * Math.cos(Math.PI * 2 / 3 * 2));
                context.lineTo(huaban.beginX + txy * Math.sin(Math.PI * 2), huaban.beginY + txy * Math.cos(Math.PI * 2));
                context.lineCap = "butt"
                context.lineJoin = "miter";
                context.closePath();
                context.stroke();
            },
            jiantouFn: function(e) {
                context.clearRect(0, 0, 1000, 480);
                drawGrid('lightgray', 10, 10);
                if (huaban.imageData != null) {
                    context.putImageData(huaban.imageData, 0, 0, 0, 0, canvas.offsetWidth, canvas.offsetHeight);
                }
                context.lineWidth = lineWidth;
                // var toX = e.pageX - canvas.offsetLeft;
                // var toY = e.pageY - canvas.offsetTop;
                var toX = e.offsetX;
                var toY = e.offsetY;
                saveDrawingSurface();
                drawLineArrow(huaban.beginX, huaban.beginY, toX, toY, color);
            }
        }
        // huaban.type = "huabi";

    // 点击事件
    huabi.onclick = function() {
        huaban.type = "huabi";
        console.log(huaban.type);
        xiancss = [];
    };
    react.onclick = function() {
        huaban.type = "react";
        console.log(huaban.type);
    };
    xianduan.onclick = function() {
        huaban.type = "xianduan";
        console.log(huaban.type);
    };
    yuan.onclick = function() {
        huaban.type = "yuan";
        console.log(huaban.type);
    };
    erase.onclick = function() {
        huaban.type = "erase";
        console.log(huaban.type);
    };
    down.onclick = function() {
        huaban.type = "down";
        console.log(huaban.type);
    };
    sanjiao.onclick = function() {
        huaban.type = "sanjiao";
        console.log(huaban.type);
        // alert('aa');
    };
    text.onclick = function() {
        huaban.type = "text";
        txtBox.style.display = 'block';
        // console.log(huaban.type);
    };
    jiantou.onclick = function() {
        huaban.type = "jiantou";
        // console.log(huaban.type);
    };
    RectangleCheckbox.onchange = function() {
        rectangle = RectangleCheckbox.checked;
    };
    for (var j = 0; j < xuxian.length; j++) {
        xuxian[0].onclick = function() {
            huaban.type = "xuxian";
            xiancss = [3, 3];
        }
        xuxian[1].onclick = function() {
            huaban.type = "xuxian";
            xiancss = [10, 10];
        }
        xu.onclick = function() {
            huaban.type = "xuxian";
            xiancss = [10, 10];
        }
        xuxian[2].onclick = function() {
            huaban.type = "xuxian";
            xiancss = [12, 3, 3];
        }
    }
    // wanggeCheckbox.onclick = function() {
    //     if (wangge == false) {
    //         drawGrid('lightgray', 10, 10);
    //         // alert('111');
    //         wangge = true;
    //     } else {
    //         context.clearRect(0, 0, 1000, 480);
    //         wangge = false;
    //     }
    // };

    // 鼠标事件
    canvas.onmousedown = function(e) {
        huaban.status = true;
        if (huaban.type == "react") {
            huaban.beginX = e.offsetX;
            huaban.beginY = e.offsetY;

        };
        if (huaban.type == "huabi") {
            // if (wangge) {
            //     drawGrid('lightgray', 10, 10);
            // }
            // console.log(e.offsetX, e.offsetY);
            context.beginPath();
            context.moveTo(e.offsetX, e.offsetY);
        };
        if (huaban.type == "xianduan") {
            huaban.beginX = e.offsetX;
            huaban.beginY = e.offsetY;
        };
        if (huaban.type == "yuan") {
            var loc = windowToCanvas(e.clientX, e.clientY);
            saveDrawingSurface();
            mousedown.x = loc.x;
            mousedown.y = loc.y;
        };
        if (huaban.type == "erase") {
            var loc = windowToCanvas(e.clientX, e.clientY);
            mousedown.x = loc.x;
            mousedown.y = loc.y;
            lastX = loc.x;
            lastY = loc.y;
        };
        if (huaban.type == "xuxian") {
            context.lineWidth = lineWidth;
            context.strokeStyle = color;
            context.beginPath();
            context.setLineDash(xiancss);
            context.moveTo(e.offsetX, e.offsetY);
        };
        if (huaban.type == "sanjiao") {
            huaban.beginX = e.offsetX;
            huaban.beginY = e.offsetY;
        };
        if (huaban.type == "jiantou") {

            huaban.beginX = e.offsetX;
            huaban.beginY = e.offsetY;
        };
        if (huaban.type == "text") {
            huaban.beginX = e.pageX - canvas.offsetLeft;
            huaban.beginY = e.pageY - canvas.offsetTop;
            context.fillText(wenben.value, posX, posY);
            wenben.style.left = huaban.beginX - 170 + "px";
            wenben.style.top = huaban.beginY + 60 + "px";
            posX = huaban.beginX - 170;
            posY = huaban.beginY + 20;
            context.font = textsize + "px" + " " + textcss; //文字大小与样式
            context.fillStyle = color;
            if (shu % 2 == 0) {
                wenben.style.display = 'block';
            }
            if (shu % 2 != 0) {
                // alert(posX, posY)
                context.beginPath();
                // 文字颜色
                context.textBaseline = 'middle';
                context.fill();
                context.closePath();
                wenben.value = '';
                wenben.style.display = 'none';
            }
            shu++;
        };
    };
    canvas.onmousemove = function(e) {
        var loc;
        if (huaban.status) {
            if (huaban.type == "yuan") {
                loc = windowToCanvas(e.clientX, e.clientY);
                context.strokeStyle = color;
                context.lineWidth = lineWidth;
                restoreDrawingSurface();
                updateRubberbandCircle(loc);
            };
            if (huaban.type == "erase") {
                loc = windowToCanvas(e.clientX, e.clientY);
                eraseLast();
                drawEraser(loc);
                lastX = loc.x;
                lastY = loc.y;

            };
            if (huaban.type != "erase" && huaban.type != "yuan" && huaban.type != "text") {
                var strFn = huaban.type + 'Fn';
                // console.log(huaban);
                huaban[strFn](e);
                if (rectangle && huaban.type != "huabi" && huaban.type != "xuxian") {
                    context.fillStyle = color;
                    context.fill();
                }
            }
        }

    }
    canvas.onmouseup = function(evt) {
        huaban.imageData = context.getImageData(0, 0, canvas.offsetWidth, canvas.offsetHeight);
        if (huaban.type == "xianduan") {
            lines.push({
                'sx': huaban.beginX,
                'sy': huaban.beginY,
                'ex': evt.offsetX,
                'ey': evt.offsetY,
            });
        };
        if (huaban.type == "yuan") {
            var loc = windowToCanvas(evt.clientX, evt.clientY);
            restoreDrawingSurface();
            updateRubberbandCircle(loc);
        }
        if (huaban.type == "erase") {
            var loc = windowToCanvas(evt.clientX, evt.clientY);
            eraseLast();
            drawEraser(loc);
        }
        huaban.status = false;
        console.log(huaban.type);
    };

    function drawOldLines() {
        for (var i = 0; i < lines.length; i++) {
            context.beginPath();
            context.moveTo(lines[i].sx, lines[i].sy);
            context.lineTo(lines[i].ex, lines[i].ey);
            // context.closePath();
            context.stroke();
        }
    };
    // 坐标转化为canvas坐标
    function windowToCanvas(x, y) {
        //返回元素的大小以及位置
        var bbox = canvas.getBoundingClientRect();
        return {
            x: x - bbox.left * (canvas.width / bbox.width),
            y: y - bbox.top * (canvas.height / bbox.height)
        };
    }
    //保存和恢复绘图面板
    function saveDrawingSurface() {
        drawingSurfaceImageData = context.getImageData(0, 0, canvas.width, canvas.height);
    }

    function restoreDrawingSurface() {
        context.putImageData(drawingSurfaceImageData, 0, 0);
    }
    // 更新橡皮筋圆形
    function updateRubberbandCircle(loc) {
        rubberbandRect.width = Math.abs(loc.x - mousedown.x);
        rubberbandRect.height = Math.abs(loc.y - mousedown.y);
        var radius;

        if (mousedown.y === loc.y) {
            radius = Math.abs(loc.x - mousedown.x);
            // console.log(radius);
        } else {
            //反正切函数
            // console.log(rubberbandRect.height + '+' + rubberbandRect.width);
            radius = Math.sqrt(Math.pow(rubberbandRect.height, 2) + Math.pow(rubberbandRect.width, 2));
        }
        context.beginPath();
        context.arc(mousedown.x, mousedown.y, radius, 0, Math.PI * 2, false);
        context.stroke();
        if (rectangle) {
            context.fillStyle = color;
            context.fill();
        }
    }

    // 橡皮擦
    function setDrawPathForEraser(loc) {
        context.beginPath();
        context.arc(loc.x, loc.y,
            50 / 2,
            0, Math.PI * 2, false);
        context.clip();
    }

    function setErasePathForEraser() {
        context.beginPath();

        context.arc(lastX, lastY,
            50 / 2 + 2,
            0, Math.PI * 2, false);
        context.clip();
    }

    function eraseLast() {
        context.save();
        setErasePathForEraser();
        // drawGrid('lightgray', 10, 10);
        context.clearRect(0, 0, context.canvas.width, context.canvas.height);
        drawGrid('lightgray', 10, 10);
        context.restore();
    }

    function drawEraser(loc) {
        context.save();
        context.lineWidth = 8;
        context.shadowBlur = 20;
        context.strokeStyle = 'transparent';
        setDrawPathForEraser(loc);
        // context.stroke();
        context.restore();
    }

    // 箭头
    function drawLineArrow(fromX, fromY, toX, toY, color) {
        // var 18 = 18; //自定义箭头线的长度
        var theta = 45; //自定义箭头线与直线的夹角，个人觉得45°刚刚好
        var arrowX, arrowY; //箭头线终点坐标
        // 计算各角度和对应的箭头终点坐标
        var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI;
        var angle1 = (angle + theta) * Math.PI / 180;
        var angle2 = (angle - theta) * Math.PI / 180;
        var topX = 18 * Math.cos(angle1);
        var topY = 18 * Math.sin(angle1);
        var botX = 18 * Math.cos(angle2);
        var botY = 18 * Math.sin(angle2);
        context.beginPath();
        //画直线
        context.moveTo(fromX, fromY);
        context.lineTo(toX, toY);

        arrowX = toX + topX;
        arrowY = toY + topY;
        //画上边箭头线
        context.moveTo(arrowX, arrowY);
        context.lineTo(toX, toY);

        arrowX = toX + botX;
        arrowY = toY + botY;
        //画下边箭头线
        context.lineTo(arrowX, arrowY);

        context.strokeStyle = color;
        context.stroke();
    }
    // 下载图片
    down.onclick = function() {
        // drawGrid('lightgray', 10, 10) = false;
        /* saveDrawingSurface();
        restoreDrawingSurface(); */
        drawingSurfaceImageData = context.getImageData(0, 0, canvas.width, canvas.height);
        context.putImageData(drawingSurfaceImageData, 0, 0);
        // 创建一个 a 标签，并设置 href 和 download 属性
        const el = document.createElement('a');
        // 设置 href 为图片经过 base64 编码后的字符串，默认为 png 格式
        el.href = canvas.toDataURL();
        el.download = '我的佳作';
        // 创建 a 标签 点击事件
        const event = new MouseEvent('click');
        el.dispatchEvent(event);
    }

    // 清空
    document.querySelector('.clear').addEventListener('click', () => {
        context.clearRect(0, 0, 1000, 480);
        huaban.imageData = null;
        // context.clearRect(0, 0, canvas.width, canvas.height);
        drawGrid('lightgray', 10, 10);
        saveDrawingSurface();
        lines = [];
    });


    // 猜词
    var ok = document.querySelector('#ok');
    var ci = document.querySelector('#ci');
    var jishi = document.querySelector('#jishi');
    var update = document.querySelector('#update');
    var sound = new Audio();
    sound.src = "mp3/ling.mp3";
    var times;
    var flag = true;
    var timerId;
    var suiji;

    function format(n) {
        if (n <= 9) {
            return '0' + n;
        } else {
            return n;
        }
    }
    ok.onclick = function() {
        if (flag) {
            times = 5;
            timerId = setInterval(function() {
                times--;
                jishi.innerHTML = '00:' + format(times % 60);
                if (times == 0) {
                    clearInterval(timerId);
                    sound.play();
                    alert('时间到！');
                }
            }, 1000)

        }
        flag = true;

    }
    update.onclick = function() {
        var xhr = new XMLHttpRequest();
        var url = "ciyu.json";
        xhr.open("GET", url);
        suiji = Math.floor(Math.random() * (35 - 0 + 1));
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200 || xhr.status == 304) {
                    // alert(xhr.readyState);
                    var result = xhr.responseText;
                    var obj = eval(("(" + result + ")"));
                    console.log(obj);
                    ci.innerHTML = obj.ciyuArr[suiji].string
                }
            }
        }
        clearInterval(timerId);
        times = 0;
        xhr.send(null);
        return false;
    };
    var music = document.getElementById('mymp3');
    var yinyue = document.querySelector('.yinyue');
    document.onclick = function() {
        music.volume = 0.05;
        music.play();
    };
}